import { h } from 'snabbdom/build/package/h';
import { init } from 'snabbdom/build/package/init';
// 下面内容请按需导入
import { classModule } from 'snabbdom/build/package/modules/class';
import { propsModule } from 'snabbdom/build/package/modules/props.js';
import { styleModule } from 'snabbdom/build/package/modules/style.js';
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners.js';

import { originalData } from './data.js';

const sortData = [
  {
    label: 'Rank',
    sort: 1
  },
  {
    label: 'Title',
    sort: 1
  },
  {
    label: 'Desc',
    sort: 1
  }
]
let counts = originalData.length;
let oldVnode = null;
const patch = init([classModule, propsModule, styleModule, eventListenersModule]);
function view(data) {
  let itemList = [];
  data.forEach((item, index) => {
    itemList.push(
      h('div.row', { key: index }, [
        h('div', item.rank),
        h('div', item.title),
        h('div', item.desc),
        h('button.btn.rm-btn', {
          on: {
            click: function () {
              data.splice(data.indexOf(item), 1);
              oldVnode = patch(oldVnode, view(data));
            }
          }
        }, 'X')
      ]));
  });
  let sortList = sortData.map((item, index) => {
    return h('button.btn', {
      key: index,
      on: {
        click: function () {
          item.sort = -item.sort;
          const prop = item.label.toLowerCase();
          data = data.sort(item.sort === 1 ? sortFn1(prop) : sortFn2(prop));
          oldVnode = patch(oldVnode, view(data));
        }
      }
    }, item.label)
  });
  let vnode = h('div', [
    h('h1', { style: { fontWeight: 700 } }, 'MOVIES-LIST'),
    h('div.head', [
      h('div', [
        h('strong', 'Sort by：'),
        ...sortList
      ]),
      h('button.btn', {
        on: {
          click: function () {
            data.unshift({
              rank: ++counts,
              title: "this is add item",
              desc: 'this is more。。。。。。',
              elmHeight: 0,
            });
            oldVnode = patch(oldVnode, view(data));
          }
        }
      }, 'add'),
    ]),
    h('div.list', itemList)
  ])
  return vnode
}

function sortFn1(prop) {
  return function (a, b) {
    if (a[prop] > b[prop]) {
      return 1;
    }
    if (a[prop] < b[prop]) {
      return -1;
    }
    return 0;
  }
}

function sortFn2(prop) {
  return function (a, b) {
    if (a[prop] < b[prop]) {
      return 1;
    }
    if (a[prop] > b[prop]) {
      return -1;
    }
    return 0;
  }
}

let app = document.querySelector('#app')
oldVnode = patch(app, view(originalData))
